<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="80px"
    >
      <el-form-item label="讲师姓名" prop="teacherName">
        <el-input
          v-model="dataForm.teacherName"
          placeholder="讲师姓名"
        ></el-input>
      </el-form-item>
      <el-form-item label="讲师邮箱" prop="teacherEmail">
        <el-input
          v-model="dataForm.teacherEmail"
          placeholder="讲师邮箱"
        ></el-input>
      </el-form-item>



      <el-form-item label="讲师头像" prop="teacherAvatar" >
        <div class="avatar-container">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:8888/api/minio/upload"
            :show-file-list="false"
            :on-preview="handlePictureCardPreview"
            :on-success="handleUploadSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img style="width: 150px;height: 150px" v-if="dataForm.teacherAvatar!==''" :src="dataForm.teacherAvatar" class="avatar" alt="">
            <el-button v-else size="small" type="primary">点击上传</el-button>
          </el-upload>
        </div>
      </el-form-item>





      <el-form-item label="讲师用户名" prop="teacherUsername">
        <el-input
          v-model="dataForm.teacherUsername"
          placeholder="讲师用户名"
        ></el-input>
      </el-form-item>
      <el-form-item label="讲师简介" prop="teacherDescription">
        <el-input
          v-model="dataForm.teacherDescription"
          placeholder="讲师简介"
        ></el-input>
      </el-form-item>

      <el-form-item label="出生日期" prop="birthday">
        <el-date-picker
          v-model="dataForm.birthday"
          type="date"
          placeholder="选择日期"
        >
        </el-date-picker>
      </el-form-item>

      <el-form-item label="性别">
        <el-radio-group v-model="dataForm.teacherGender">
          <el-radio label="男"></el-radio>
          <el-radio label="女"></el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="讲师学历" prop="teacherLevelName">
        <el-select v-model="dataForm.teacherLevelName" placeholder="请选择">
          <el-option
            v-for="item in levelOptions"
            :key="item.id"
            :label="item.teacherLevelName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="讲师类型" prop="teacherTypeName">
        <el-select v-model="dataForm.teacherTypeName" placeholder="请选择">
          <el-option
            v-for="item in typeOptions"
            :key="item.id"
            :label="item.teacherTypeName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  data () {
    return {
      visible: false,
      dataForm: {
        id: 0,
        teacherName: '',
        teacherEmail: '',
        teacherAvatar: '',
        teacherHover: '',
        teacherUsername: '',
        teacherPassword: '',
        teacherDescription: '',
        birthday: '',
        teacherGender: '',
        teacherLevelName: '',
        teacherTypeName: '',
        createTime: '',
        updateTime: '',
        status: '',
        isDelete: ''
      },
      fileList: [
        {
          name: '',
          url: ''
        }
      ],
      imageUrl: '',
      flag: true,
      levelOptions: [],
      typeOptions: [],
      dataRule: {
        teacherName: [
          { required: true, message: '讲师姓名不能为空', trigger: 'blur' }
        ],
        teacherEmail: [
          { required: true, message: '讲师邮箱不能为空', trigger: 'blur' }
        ],
        teacherAvatar: [
          { required: false, message: '讲师头像不能为空', trigger: 'blur' }
        ],
        teacherHover: [
          { required: false, message: '讲师封面不能为空', trigger: 'blur' }
        ],
        teacherUsername: [
          { required: true, message: '讲师用户名不能为空', trigger: 'blur' }
        ],
        teacherPassword: [
          { required: false, message: '讲师密码不能为空', trigger: 'blur' }
        ],
        teacherDescription: [
          { required: true, message: '讲师简介不能为空', trigger: 'blur' }
        ],
        birthday: [
          { required: true, message: '讲师生日不能为空', trigger: 'blur' }
        ],
        teacherLevelName: [
          { required: true, message: '讲师学历不能为空', trigger: 'blur' }
        ],
        teacherTypeName: [
          { required: true, message: '讲师类型不能为空', trigger: 'blur' }
        ],
        createTime: [
          { required: false, message: '创建时间不能为空', trigger: 'blur' }
        ],
        updateTime: [
          { required: false, message: '修改时间不能为空', trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    init (id) {
      this.getTeacherLevel();
      this.getTeacherType();
      console.log(this.dataForm.teacherLevelName, 'ssadsa');

      this.dataForm.id = id || 0;
      this.visible = true;
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields();
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(
              `/teacher/teacher/findTeacherDetailById/${this.dataForm.id}`
            ),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({ data }) => {
            if (data && data.code === 0) {
              console.log(data.detail, 'sad')
              console.log(data.detail.teacherLevelName, 'sad')
              this.dataForm.teacherName = data.detail.teacherName;
              this.dataForm.teacherEmail = data.detail.teacherEmail;
              this.dataForm.teacherAvatar = data.detail.teacherAvatar;
              this.dataForm.teacherHover = data.detail.teacherHover;
              this.dataForm.teacherUsername = data.detail.teacherUsername;
              this.dataForm.teacherPassword = data.detail.teacherPassword;
              this.dataForm.teacherDescription =
              data.detail.teacherDescription;
              this.dataForm.birthday = data.detail.birthday;
              this.dataForm.teacherLevelName = data.detail.teacherLevelName;
              this.dataForm.teacherTypeName = data.detail.teacherTypeName;
              this.dataForm.createTime = data.detail.createTime;
              this.dataForm.updateTime = data.detail.updateTime;
              this.dataForm.status = data.detail.status;
              this.dataForm.isDelete = data.detail.isDelete;
              this.dataForm.teacherGender = data.detail.teacherGender;
            }
          });
        }
      });
    },
    // 表单提交
    dataFormSubmit () {
      this.$refs['dataForm'].validate((valid) => {
        this.setLevelId()
        this.setTypelId()
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(
              `/teacher/teacher/${!this.dataForm.id ? 'save' : 'update'}`
            ),
            method: 'post',
            data: this.$http.adornData({
              id: this.dataForm.id || undefined,
              teacherName: this.dataForm.teacherName,
              teacherEmail: this.dataForm.teacherEmail,
              teacherAvatar: this.dataForm.teacherAvatar,
              teacherHover: this.dataForm.teacherHover,
              teacherUsername: this.dataForm.teacherUsername,
              teacherPassword: this.dataForm.teacherPassword,
              teacherDescription: this.dataForm.teacherDescription,
              birthday: this.dataForm.birthday,
              teacherLevelName: this.dataForm.teacherLevelName,
              teacherTypeName: this.dataForm.teacherTypeName,
              createTime: this.dataForm.createTime,
              updateTime: this.dataForm.updateTime,
              status: this.dataForm.status,
              isDelete: this.dataForm.isDelete,
              teacherGender: this.dataForm.teacherGender
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit('refreshDataList');
                }
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    },
    // 获取讲师学历等级数据
    getTeacherLevel () {
      this.$http({
        url: this.$http.adornUrl('/teacher/teacherlevel/findTeacherLevelList'),
        method: 'get'
      }).then(({ data }) => {
        if (data && data.code === 0) {
          console.log(data.teacherLevelList);
          this.levelOptions = data.teacherLevelList;
        } else {
          this.levelOptions = [];
        }
      });
    },

    // 打开编辑框的时候为等级和类型设置对应的id
    setLevelId () {
      if (typeof this.dataForm.teacherLevelName === 'string') {
        for (var i = 0; i < this.levelOptions.length; i++) {
          if (
            this.dataForm.id &&
            this.dataForm.teacherLevelName === this.levelOptions[i].teacherLevelName
          ) {
            this.dataForm.teacherLevelName = this.levelOptions[i].id;
          }
          console.log(this.dataForm.teacherLevelName, 'sadas');
        }
      }
    },

    setTypelId () {
      if (typeof this.dataForm.teacherTypeName === 'string') {
        for (var i = 0; i < this.typeOptions.length; i++) {
          if (
            this.dataForm.id &&
            this.dataForm.teacherTypeName === this.typeOptions[i].teacherTypeName
          ) {
            this.dataForm.teacherTypeName = this.typeOptions[i].id;
          }
          console.log(this.dataForm.teacherTypeName, 'sadas');
        }
      }
    },

    // 获取讲师类型数据
    getTeacherType () {
      this.$http({
        url: this.$http.adornUrl('/teacher/teachertype/findTeacherTypeList'),
        method: 'get'
      }).then(({ data }) => {
        if (data && data.code === 0) {
          console.log(data.teacherTypeList);
          this.typeOptions = data.teacherTypeList;
        } else {
          this.typeOptions = [];
        }
      });
    },
    handlePreview (file) {
      console.log(file);
    },

    handleRemove (file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview (file) {
      console.log(file);
      this.dataForm.teacherAvatar = file.url;
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleUploadSuccess (res, file) {
      console.log(res, 'res')
      console.log(file, 'file')
      this.dataForm.teacherAvatar = res.msg

      // this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload (file) {
      console.log(file.type, 'file')
      const isJPG = file.type === 'image/jpeg';
      const isPng = file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG && !isPng) {
        this.$message.error('上传头像图片只能是 JPG或PNG格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return (isJPG || isPng) && isLt2M;
    },
    updateFlag () {
      this.flag = this.dataForm.teacherAvatar !== '';
      console.log(this.flag);
    },
    close () {
      this.visible = false;
      this.handleRemove(this.fileList);
    }
  }
};
</script>
<style>
.avatar-container {
  display: flex;
}

</style>
